package ch3;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;

public class SetOfStacks{
	
	private LinkedList<MyStack<Integer>> stacks = new LinkedList<MyStack<Integer>>();
	private int count;
	private final int size = 3;
	
	public SetOfStacks(){
		count = -1;
	}
	
	public int numberOfStack()
	{
		return stacks.size();
	}
	
	public void push(int value){
		if(count == -1||!stacks.getLast().isAtCapacity()){
			++count;
			MyStack<Integer> stack = new MyStack<Integer>(size);
			stack.push(value);
			stacks.addLast(stack);			
		}
		else{
			stacks.getLast().push(value);
		}
	}
	
//	public void push(int value)
//	{
//		if(elementCount % size == 0){
//			++count;
//			Stack<Integer> stack = new Stack<Integer>();
//			stack.add(value);
//			stacks.add(stack);
//			++elementCount;
//		}
//		else{
//			stacks.get(count).push(value);
//			++elementCount;
//		}
//		System.out.println("count: "+count +"	elementCount: "+elementCount);
//	}
//	
	
	public Object pop(){
		Object result = null;
		if(count == -1)
			return result;
		else{
			result = stacks.getLast().pop();
			if(stacks.getLast().isEmpty()){
				stacks.removeLast();
				--count;
			}
			return result;
		}
		
	}
	
	public void print()
	{
		Iterator it = stacks.iterator();
		while(it.hasNext()){
			MyStack<Integer> stack = (MyStack<Integer>) it.next();
			Object[] temp = stack.toArray();
			for(int i = 0; i != temp.length; ++i)
				System.out.print(temp[i]+" ");
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] elements = {7,4,2,1,5,8,2,3,5,8,0,3,5};
		SetOfStacks stack = new SetOfStacks();
		for(int i = 0; i != elements.length; ++i){
			stack.push(elements[i]);
			System.out.println("after push "+elements[i]);
			stack.print();
		}
		for(int i = 0 ; i != 6; ++i)
		{
			System.out.println("after pop "+i+"\tHere is "+stack.numberOfStack()+"stacks");
			stack.pop();
			stack.print();
		}
		
		System.out.println("Here is "+stack.numberOfStack()+"stacks");
		
	}

}
